package com.qmyx.supply.admin.utils;


import com.aliyun.oss.OSSClient;
import com.aliyun.oss.model.ObjectMetadata;
import com.aliyun.oss.model.PutObjectRequest;
import com.qmyx.supply.admin.constants.OSSClientConstants;
import com.qmyx.supply.admin.model.response.FileResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.Objects;
import java.util.UUID;

/**
 * 
 * @version 1.0
 * @description 阿里云 oss 对象存储 工具类
 **/
@Component
@Slf4j
public class AliyunOSSClientUtil {

    //oss参数实体类
    private static OSSClientConstants ossEntity;

    public OSSClientConstants getOssEntity() {
        return ossEntity;
    }

    public void setOssEntity(OSSClientConstants ossEntity) {
        this.ossEntity = ossEntity;
    }
    /**
     * 获取阿里云OSS客户端对象 (初始化)
     *
     * @return ossClient
     */
    public static OSSClient getOSSClient() {
        return new OSSClient(ossEntity.getEndPoint(), ossEntity.getAccessKeyId(), ossEntity.getAccessKeySecret());
    }



    /**
     * 根据key删除OSS服务器上的文件
     *
     * @param ossClient  oss连接
     * @param bucketName 存储空间
     * @param folder     模拟文件夹名 如"qj_nanjing/"
     * @param key        Bucket下的文件的路径名+文件名 如："default/123.jpg"
     */
    public static void deleteFile(OSSClient ossClient, String bucketName, String folder, String key) {
        ossClient.deleteObject(bucketName, folder + key);
        log.info("删除" + bucketName + "下的文件" + folder + key + "成功");
    }


    /**
     * 上传图片至OSS
     *
     * @param ossClient oss连接
     * @param file      MultipartFile 文件
     * @param folder    指定上传文件夹路径
     * @return FileDto   上传结果
     */
    public static FileResponse uploadObject2OSS(OSSClient ossClient, MultipartFile file, String folder) {
        return uploadObject2OSS(ossClient, file, ossEntity.getBacketName(), folder);
    }

    /**
     * 上传图片至OSS
     *
     * @param ossClient oss连接
     * @param file      MultipartFile 文件
     * @return FileDto   上传结果
     */
    public static FileResponse uploadObject2OSS(OSSClient ossClient, MultipartFile file) {
        return uploadObject2OSS(ossClient, file, ossEntity.getBacketName(), ossEntity.getFolder());
    }

    /**
     * 上传图片至OSS
     *
     * @param ossClient  oss连接
     * @param file       MultipartFile 文件
     * @param bucketName 存储空间
     * @param folder     文件夹名称
     * @return FileDto   上传结果
     */
    public static FileResponse uploadObject2OSS(OSSClient ossClient, MultipartFile file, String bucketName, String folder) {
        log.info("  上传参数bucketName , folder ===> " + bucketName + " , " + folder);
        FileResponse dto = new FileResponse();
        try {
            StringBuilder fileUrl = new StringBuilder();
            String suffix = Objects.requireNonNull(file.getOriginalFilename()).substring(file.getOriginalFilename().lastIndexOf('.'));
            String point = ".";
            String uuid = UUID.randomUUID().toString().replaceAll("-","");
            dto.setSize(file.getSize());
            dto.setId(uuid);
            dto.setName(file.getOriginalFilename());

            if (!suffix.startsWith(point)) {
                suffix = point + suffix;
            }
            String fileName = uuid + suffix;
            if (!folder.endsWith("/")) {
                folder = folder.concat("/");
            }
            fileUrl.append(folder).append(fileName);

            // 创建PutObjectRequest对象。
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, fileUrl.toString(), file.getInputStream());
            // 如果需要上传时设置存储类型和访问权限，请参考以下示例代码。
            ObjectMetadata metadata = new ObjectMetadata();
            metadata.setHeader("referer", "http://admin.cn");
//             metadata.setObjectAcl(CannedAccessControlList.Private);
            putObjectRequest.setMetadata(metadata);
            ossClient.putObject(putObjectRequest);

            // 文件url
            dto.setUrl(getFileUrl(fileName, folder));
            log.info("文件上传成功 ===>" + dto.getName());
            return dto;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static FileResponse uploadExcel2OSS(OSSClient ossClient, InputStream inputStream){
        return uploadExcel2OSS(ossClient, inputStream, ossEntity.getBacketName(), ossEntity.getFolder());
    }

    /**
     * 上传图片至OSS
     *
     * @param ossClient  oss连接
     * @param bucketName 存储空间
     * @param folder     文件夹名称
     * @return FileDto   上传结果
     */
    public static FileResponse uploadExcel2OSS(OSSClient ossClient, InputStream inputStream, String bucketName, String folder) {
        log.info("  上传参数bucketName , folder ===> " + bucketName + " , " + folder);
        FileResponse dto = new FileResponse();
        try {
            StringBuilder fileUrl = new StringBuilder();
            String uuid = UUID.randomUUID().toString().replaceAll("-","");
            dto.setId(uuid);
            String fileName = uuid + ".xlsx";
            if (!folder.endsWith("/")) {
                folder = folder.concat("/");
            }
            fileUrl.append(folder).append(fileName);

            // 创建PutObjectRequest对象。
            PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, fileUrl.toString(),inputStream);
            // 如果需要上传时设置存储类型和访问权限，请参考以下示例代码。
            ObjectMetadata metadata = new ObjectMetadata();
            metadata.setHeader("referer", "http://admin.cn");
//             metadata.setObjectAcl(CannedAccessControlList.Private);
            putObjectRequest.setMetadata(metadata);
            ossClient.putObject(putObjectRequest);

            // 文件url
            dto.setUrl(getFileUrl(fileName, folder));
            log.info("文件上传成功 ===>" + dto.getName());
            return dto;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }



    /**
     * 拼接文件url
     *
     * @param fileName 文件名称
     * @return url
     */
    public static String getFileUrl(String fileName, String FOLDER) {
         return "https://" + ossEntity.getEndPoint() + "/" + FOLDER  + fileName;
        //return "http://" + ENDPOINT + "/" + folder + fileName;
    }

}
